package android.development;

import android.app.Activity;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class MainGamePanel extends SurfaceView implements
SurfaceHolder.Callback 
{
	private MainThread thread;
	private Droid droid;
	
	private static final String TAG = MainGamePanel.class.getSimpleName();
	
	public MainGamePanel( Context context ) 
	{
		super( context );
		// adding the callback (this) to the surface holder to
		// intercept events
		getHolder().addCallback(this);
		
		// Create the droid and load bitmap
		droid = new Droid( BitmapFactory.decodeResource(getResources(), R.drawable.droid_1), 50, 50);
		
		// Create the game loop thread
		thread = new MainThread(getHolder(), this);
		
		// make the GamePanel focusable so it can handle
		// events
		setFocusable(true);
	}
	
	public void surfaceChanged( SurfaceHolder holder,
			int format, int width, int height)
	{
		
	}
	
	public void surfaceCreated( SurfaceHolder holder )
	{
		thread.setRunning(true);
		thread.start();
	}
	
	public void surfaceDestroyed( SurfaceHolder holder )
	{
		Log.d(TAG, "Surface is being destroyed");
		// Tell the thread to shut down and wait for it to finish
		// This is a clean shutdown
		boolean retry = true;
		while( retry )
		{
			try
			{
				thread.join();
				retry = false;
			}
			catch( InterruptedException e)
			{
				// Try again shutting down the thread
			}
		}
		Log.d(TAG, "Thread was shut down cleanly");
	}
	
	public boolean onTouchEvent( MotionEvent event )
	{
		if( event.getAction() == MotionEvent.ACTION_DOWN )
		{
			// delegating event handling to the droid
			droid.handleActionDown((int)event.getX(), (int)event.getY());
			
			// Check if it is in the lower part of the screen
			// then exit if that's the case
			if( event.getY() > getHeight() - 50 )
			{
				thread.setRunning(false);
				( (Activity )getContext() ).finish();
			}
			else 
			{
				Log.d(TAG, "Coords: x=" + event.getX() +
						 ",y=" + event.getY());
			}
		}
		if( event.getAction() == MotionEvent.ACTION_MOVE )
		{
			// The gestures
			if( droid.isTouched() )
			{
				// The droid was picked up and is
				// being dragged
				droid.setX((int)event.getX());
				droid.setY((int)event.getY());
			}
			if( event.getAction() == MotionEvent.ACTION_UP)
			{
				// Touch was released
				if( droid.isTouched() )
				{
					droid.setTouched(false);
				}
			}
		}
		return true;
	}
	
	protected void onDraw( Canvas canvas )
	{
		canvas.drawColor(Color.BLACK);
		droid.draw(canvas);
	}
}
